<?php


namespace app\user\controller;


use app\admin\model\AccountStatus;
use app\user\logic\ShareLinkLogic;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Messages\Article;
use GuzzleHttp\Exception\GuzzleException;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Request;
use app\common\model\MiniApp as MiniAppModel;
use app\common\model\WechatShareLink as WechatShareLinkModel;

class WechatShareLink extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class',
        'app\http\middleware\checkUserAuth::class'
    ];


    public function userList()
    {

        $app = Factory::officialAccount(ShareLinkLogic::getAccount());
        $list= $app->user->list();  // $nextOpenId 可选
        $list2=[];
        foreach ($list->data->openid as $item) {
            $user = $app->user->get($item);
            array_push($list2,$user);
        }

        $this->result($list2,200);
    }


    //获取素材的短连接
    private function getLongUrl($long_url)
    {

        $curl = curl_init();
//        $long_url=   "http://mp.weixin.qq.com/s?__biz=MzI5MDQyMTEzMw==&mid=100000058&idx=1&sn=df035850513c96a8e8a92077a955b274&chksm=6c2161d85b56e8ceea93a7d32b18f83e00243b9ccc33e4f9f53eb08d4d435d607a763945ed0c#rd";

        $post_url = "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&" . substr($long_url, 26);

        curl_setopt_array($curl, array(
//            CURLOPT_URL => "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&__biz=MzI5MDQyMTEzMw==",
            CURLOPT_URL => $post_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "referer: " . $long_url,
                "Cookie: rewardsn=; wxtokenkey=777"
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $obj = json_decode($response);

        return $obj->appmsg_compact_url;
//        $this->result( $obj,200);
//        echo $response;
    }

    public function index()
    {
        $page=Request::param('page',1);
        $user_id=Request::param('user_id',1);
        $list=WechatShareLinkModel::where('user_id',$user_id)->page($page,15)
            ->leftJoin('ad_play_history','wechat_share_link.id=ad_play_history.url_id')
            ->field(['wechat_share_link.*' ])
            ->group('wechat_share_link.id')
            -> select();
        $this->result($list,200);
    }

    //判断是否已经生成过该链接了
    public function hasLink($mini_app_code,$product_id)
    {
        $user_id = Request::param('user_id');
        $res= WechatShareLinkModel::hasLink($user_id,$mini_app_code,$product_id);
        $this->result($res,200);
    }

    //生成素材链接
    private function createMaterialLink($user_id,$mini_app_code,$title,$product_id)
    {
        //微信小程序的信息
        $mini_app = MiniAppModel::where('code', $mini_app_code)->find();

        $config = ShareLinkLogic::getAccount();
        $app = Factory::officialAccount($config);

        //跳转的链接
        $path="pages/index/index?product_id=$product_id&promote_user_id=$user_id&mini_app_code=$mini_app_code";

        // 上传单篇图文
        $article = new Article([
            'title' => $title,
            'thumb_media_id' => ShareLinkLogic::getCoverMediaId(),
            'show_cover' => 0, // 是否在文章内容显示封面图片
            "content_source_url" => 'http://www.baidu.com',
            'content' => ShareLinkLogic::getArticleContent($mini_app,$path,$user_id),
        ]);

        try {
            $res2 = $app->material->uploadArticle($article);
        } catch (InvalidConfigException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        } catch (GuzzleException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        }

        //素材管理
        try {
            $resource = $app->material->get($res2->media_id);
        } catch (InvalidConfigException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        } catch (GuzzleException $e) {
            $this->result($e->getMessage(), 400, '失败，请稍后再试');
        }

        $long_url = $resource->news_item[0]->url;

        $url = $this->getLongUrl($long_url);

        $data = [
//                'media_id'=>$res2->media_id,        //素材的id
//                "long_url"=>$long_url,
            'user_id'=>$user_id,
            'app_id'=>$config['app_id'],
            'created_id'=>$user_id,
            'mini_app_code'=>$mini_app_code,
            "product_id"=>$product_id,
            'title'=>$title,
            "url" => $url,
            'add_time'=>time()
        ];

        //存数据库
        $res2=WechatShareLinkModel::create( $data);

        return $data;
    }

    //生成文章链接
    public function createArticleLink( $user_id,$mini_app_code,$title,$product_id)
    {
        //注意：生成链接需要公众号为服务号，且粉丝数量大于2

        //微信小程序的信息
        $mini_app = MiniAppModel::where('code', $mini_app_code)->find();

        //获取数据库公众号，配置文件
//        $config = Config::get('miniprogram.officialAccount');
        $config = ShareLinkLogic::getAccount();

//        die(json_encode($config));

        $app = Factory::officialAccount($config);
        $no=rand(20000000,99999999). time();

        $user_info=\app\user\model\User::get($user_id);

        //判断程序是否是会员专享
        if ($mini_app->vip==1 && $user_info->vip<=0){
            $this->result('',400,'该产品是会员专享，请先升级会员');
        }

        //跳转的链接
        $path="pages/test/answer?product_id=$product_id&promote_user_id=$user_id&mini_app_code=$mini_app_code&no=$no";

        // 上传单篇图文
        $article = new Article([
            'title' => $title,
            'thumb_media_id' => ShareLinkLogic::getCoverMediaId(),
            'show_cover' => 0, // 是否在文章内容显示封面图片
            "content_source_url" => ShareLinkLogic::getContentSourceUrl(),
            'content' => ShareLinkLogic::getArticleContent($mini_app,$path,$user_id),
        ]);

        try{
            $res2 = $app->material->uploadArticle($article);
            $res= $app->broadcasting->sendNews($res2->media_id,  ShareLinkLogic::getPushOpenids());
            //超出公众号最大限制
            if($res->errcode == 45009){
                //异常记录公众号id
                $account_id = AccountStatus::where([
                    ['app_id', '=', $config['app_id']],
                    ['add_time', 'BETWEEN', today()]
                ])->find();
                if (empty($account_id)) {
                    $account = new AccountStatus();
                    $account->app_id = $config['app_id'];
                    $account->status = 0;
                    $account->add_time = time();
                    $re = $account->save();
                }
                //清除缓存
                Cache::rm('cover_media_id');
                Cache::rm('test_cover_url');
                Cache::rm('openids');
                Cache::rm('cover_url');
                Cache::rm('test_cover_url');
                $this->result(0, 400, '生成链接超出最大值，请重试');
            }
        }catch (Exception $e){
            dump($e->getMessage());
            //清除缓存
            Cache::rm('cover_media_id');
            Cache::rm('test_cover_url');
            Cache::rm('openids');
            Cache::rm('cover_url');
            Cache::rm('test_cover_url');
        }

           try{
               $msg_id=$res->msg_id ;
           }catch (Exception $e){
               $this->result($res,400,'生成失败app_id,secret不匹配');
           }
        $data = [
            'user_id'=>$user_id,
            'created_id'=>$user_id,
            'app_id'=>$config['app_id'],
            'no'=>$no,
            'mini_app_code'=>$mini_app_code,
            "product_id"=>$product_id,
            'title'=>$title,
            'msg_id'=> $msg_id,
            "url" => '',
            'add_time'=>time()
        ];

        //存数据库
        $res2=WechatShareLinkModel::create( $data);

        try{
            for($i=0;$i<40;$i++){
                sleep(1);
                $link=WechatShareLinkModel::where('msg_id',$msg_id)->find();
                if($link && $link->url!=''){
                   // $this->result($link,200,'成功');
                    return $link;
                }
            }
            $link=WechatShareLinkModel::where('msg_id',$msg_id)->delete();
        }catch (\Exception $e){
            //链接生成失败了，请重试
            return 0;
        }

       //链接生成失败了，请重试
        return 0;
    }

    //生成链接
    public function create()
    {
        $user_id = Request::param('user_id');
        $mini_app_code = Request::param('mini_app_code');
        $title = Request::param('title', 0);
        $product_id = Request::param('product_id', 0);      //功能的id  单功能小程序，直接上传
        $is_new = Request::param('is_new', 1);              //1的时候生成文章链接，0的时候生成素材链接
        $link=WechatShareLinkModel::hasLink($user_id,$mini_app_code,$product_id);

        //已经生成过链接了，直接返回
        if($link){
            if ($link->url){
                $this->result($link,200);
            }else{
                $this->result($link,400,'链接还在生成中，请稍后再试');
            }
        }

        //生成链接钱判断次数是否上限
        if(!ShareLinkLogic::checkMaxLink($user_id)){
             $this->result(0,4003,'今天生成的链接数已经达到了最大值');
        }

        $res= $this->createArticleLink($user_id,$mini_app_code,$title,$product_id);

        if($res){
            $this->result($res,200,'成功');
        }else{
            $this->result($res,400,'链接生成失败');
        }

    }


}
